package com.lsq.service;

import com.lsq.annotation.LsqValue;
import com.spring.BeanPostProcessor;
import com.spring.annotation.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 请描述当前类的作用
 *
 * @author LSQ
 * @since 2023/2/13 21:10
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println(beanName + " 初始化前...");


        // 实现 @LsqValue的功能
        for (Field field : bean.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(LsqValue.class)) {
                field.setAccessible(true);
                try {
                    field.set(bean, field.getAnnotation(LsqValue.class).value());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }


        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        System.out.println(beanName + " 初始化后...");

        // 实现AOP的例子 基于JDK的动态代理
        if ("userService".equals(beanName)) {
            System.out.println(beanName + " 基于JDK进行动态代理...");
            Object proxyInstance = Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    // 在这里实现切面逻辑
                    System.out.println(beanName + " 切面逻辑...");

                    // 执行具体的方法
                    return method.invoke(bean, args);

                }
            });

            // 最终创建出来的bean是这个代理对象！
            return proxyInstance;
        }

        return bean;
    }

}
